package com.google.code

import scalax.io.Resource
import scala.io.Source
import scala.util.{Success, Failure, Try}
import java.io.{FileNotFoundException, File}
import com.google.code.XmlParser.MalformedXMLException

object Menu extends App {
  def openFile(path: String): File = {
    val file = new File(path)
    if(file.exists && file.isFile)
      file
    else
      throw new FileNotFoundException()
  }

  def newFile(path:String): Option[XmlDocument] = {
    val file = new File(path)

    if(file.exists && file.isFile) {
      println(s"File already exists ($path). Do you want to overwrite it? (y/n)")
      val ch = readChar()
      if(ch == 'y') {
        file.delete()
        Some(XmlDocument.empty(new File(path)))
      }
      else None
    }
    else
      Some(XmlDocument.empty(new File(path)))
  }

  def exit(): Unit = ()

  def printMenu(): Unit = {
    println("1. Open a file")
    println("2. Create new file")
    println("9. Exit")
  }

  def menuLoop(option: String): Unit = option match {
      case "1" =>
        print("Path to the file to open: ")
        val file = readLine()
        try {
          XmlParser.parse(openFile(file)) map UserControl.run
        }
        catch {
          case ex: FileNotFoundException =>
            println("The file doesn't exist.")
            printMenu()
            menuLoop(readLine())
          case ex: MalformedXMLException =>
            println("The XML file is not of correct syntax.")
            printMenu()
            menuLoop(readLine())
          case ex: Throwable =>
            println("Something went terribly wrong!")
            printMenu()
            menuLoop(readLine())
        }

      case "2" =>
        print("Path to new file: ")
        val file = readLine()
        newFile(file) match {
          case None =>
            printMenu()
            menuLoop(readLine())

          case Some(doc) =>
            UserControl.run(doc)
        }

      case "3" =>

      case _ =>
        println("Invalid option")
        printMenu()
        menuLoop(readLine())
  }

  printMenu()
  menuLoop(readLine())
}
